package com.sdy.dcsb.web.util;

import com.sdy.common.utils.StringUtil;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 中文字符处理工具类
 * @author Snaky
 * @date 2020/4/27
 */
public class ChineseUtil {
    /** 中文字符正则表达式 */
    private static final Pattern PATTERN_CHINESE = Pattern.compile("[\u4e00-\u9fa5]");

    /**
     * 包含中文字符判断
     * @param str 源字符串
     * @return 匹配结果
     */
    public static boolean hasContainChinese(String str) {
        Matcher m = PATTERN_CHINESE.matcher(str);
        return m.find();
    }


    /**
     * 将字符串中的中文替换为urlEncode编码并返回新的字符串
     * @param str 源字符
     * @return 替换后字符串
     */
    public static String urlEncodeChinese(String str){
        if(StringUtil.isBlank(str)){
            return str;
        }
        Matcher m = PATTERN_CHINESE.matcher(str);
        StringBuffer b = new StringBuffer();
        try {
            while (m.find()) {
                m.appendReplacement(b, URLEncoder.encode(m.group(0), "utf-8"));
            }
            m.appendTail(b);
            return b.toString();
        } catch (Exception e){
            e.printStackTrace();
            return str;
        }
    }

    /**
     * 对字符串循环进行decode
     * @param decodeStr 源字符串
     * @return decode后字符串
     */
    public static String decode(String decodeStr){
        if(StringUtil.isBlank(decodeStr)){
            return decodeStr;
        }
        try {
            String str = URLDecoder.decode(decodeStr,"utf-8");
            while(!str.equals(decodeStr)){
                decodeStr = str;
                str = URLDecoder.decode(decodeStr,"utf-8");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return decodeStr;
    }
}
